package cn.edu.scau.cmi.zengGuanSheng.hibernate.client;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.input.MouseEvent;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import cn.edu.scau.cmi.zengGuanSheng.hibernate.dao.StudentDao;
import cn.edu.scau.cmi.zengGuanSheng.hibernate.dao.TeacherDao;
import cn.edu.scau.cmi.zengGuanSheng.hibernate.domain.Student;
import cn.edu.scau.cmi.zengGuanSheng.hibernate.domain.Teacher;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;

import javafx.scene.control.ListView;

public class HibernateSceneController {
	@FXML
	private TextField tF_StuNo_Add;
	@FXML
	private TextField tF_StuName_Add;
	@FXML
	private Button btn_AddStu;
	@FXML
	private TextField tF_TeachNo_Add;
	@FXML
	private TextField tF_TeachName_Add;
	@FXML
	private Button btn_AddTeach;
	@FXML
	private TextField tF_StuNo_Edit;
	@FXML
	private TextField tF_StuNo_ShowAndEdit;
	@FXML
	private TextField tF_StuName_ShowAndEdit;
	@FXML
	private TextField tF_TutorName_ShowAndEdit;
	@FXML
	private Button btn_EditStu_Save;
	@FXML
	private Button btn_showStu;
	@FXML
	private TextField tF_StuNo_del;
	@FXML
	private Button btn_DelStu;
	@FXML
	private TextField tF_TeachNo_Del;
	@FXML
	private Button btn_DelTeach;
	@FXML
	private TextField tF_TutorNo;
	@FXML
	private TextField tF_TeachedStuNo;
	@FXML
	private Button btn_Tutor_Teach_Stu_Save;
	@FXML
	private TextField tF_TeacherNo_edit;
	@FXML
	private TextField tF_TeachNo_ShowAndEdit;
	@FXML
	private TextField tF_TeachName_ShowAndEdit;
	@FXML
	private Button btn_ShowTeach;
	@FXML
	private ListView<String> listView_TeachedStu;
	@FXML
	private Button btn_EditTeacher_Save;

	private ObservableList<String> list = FXCollections.observableArrayList();
	
	/**
	 * 添加学生
	 * 
	 * @param event
	 */
	// Event Listener on Button[#btn_AddStu].onAction
	@FXML
	public void eventAddStu(ActionEvent event) {
		// TODO Autogenerated
		long stuNo = 0;
		String stuName = null;
		try {
			stuNo = Long.parseLong(tF_StuNo_Add.getText());// 获取学生的学号
			stuName = tF_StuName_Add.getText();// 获取学生的姓名
			Student stu = new Student();
			stu.setId(stuNo);
			stu.setName(stuName);
			StudentDao.addStudent(stu);

			tF_StuNo_Add.setText(null);
			tF_StuName_Add.setText(null);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText("学号：" + stuNo + "姓名：" + stuName + "的学生添加成功！");
			alert.showAndWait();
		} catch (NumberFormatException e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("警告");
			alert.setHeaderText(null);
			alert.setContentText("输入格式有误");
			alert.showAndWait();
		}
	}

	/**
	 * 添加教师
	 * 
	 * @param event
	 */
	// Event Listener on Button[#btn_AddTeach].onAction
	@FXML
	public void eventAddTeach(ActionEvent event) {
		// TODO Autogenerated
		long teachNo = 0;
		String teachName = null;
		try {
			teachNo = Long.parseLong(tF_TeachNo_Add.getText());// 获取教师的工号
			teachName = tF_TeachName_Add.getText();// 获取教师的姓名
			Teacher t = new Teacher();
			t.setId(teachNo);
			t.setName(teachName);
			TeacherDao.addTeacher(t);

			tF_TeachNo_Add.setText(null);
			tF_TeachName_Add.setText(null);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText("工号：" + teachNo + "姓名：" + teachName + "的教师添加成功！");
			alert.showAndWait();
		} catch (NumberFormatException e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("警告");
			alert.setHeaderText(null);
			alert.setContentText("输入格式有误");
			alert.showAndWait();
		}
	}
	
	/**
	 * 保存修改的学生信息，包括修改学生，学生选择指导教师，学生修改指导教师
	 * @param event
	 */
	// Event Listener on Button[#btn_EditStu_Save].onAction
	@FXML
	public void eventEditStuSave(ActionEvent event) {
		// TODO Autogenerated
		long stuNo = 0;
		String stuName = null;
		String tutorName = null;
		try {
			stuNo = Long.parseLong(tF_StuNo_ShowAndEdit.getText());// 获取修改的学生的学号
			stuName = tF_StuName_ShowAndEdit.getText();//获取修改的学生的姓名
			tutorName = tF_TutorName_ShowAndEdit.getText();//获取修改的学生的指导教师的姓名
			System.out.println("ni"+tutorName+"hh");
			Student stu = new Student();
			stu.setId(stuNo);
			stu.setName(stuName);
			
			Teacher t = new Teacher();
			t.setName(tutorName);
			if(tutorName.equals("")) {
				stu.setTeacher(null);
			}else {
				Teacher t1 = TeacherDao.findTeacherByName(t);
				stu.setTeacher(t1);
			}
			
			StudentDao.saveEdit(stu);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText("修改成功！");
			alert.showAndWait();
		}catch(IndexOutOfBoundsException e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("对不起没有这个教师！请重新输入");
			alert.showAndWait();
		}
		
	/*	Student stu1 = StudentDao.findStudentById(stu);
		
		stu1.setName(stuName);
		stu1.setTeacher(t);
		StudentDao.saveEdit(stu1);*/
	}
	/**
	 * 根据输入的学生学号，显示该学生的相关信息：学号、姓名、指导教师姓名
	 * @param event
	 */
	// Event Listener on Button[#btn_showStu].onAction
	@FXML
	public void eventShowStu(ActionEvent event) {
		// TODO Autogenerated
		long stuNo = 0;
		try {
			tF_StuNo_ShowAndEdit.setDisable(false);//恢复可编辑
			stuNo = Long.parseLong(tF_StuNo_Edit.getText());// 获取需要修改的学生的学号
			Student stu = new Student();
			stu.setId(stuNo);
			Student stu1 = StudentDao.findStudentById(stu);
//			System.out.println(stu1.getTeacher().getName());
			tF_StuNo_ShowAndEdit.setText(Long.toString(stu1.getId()));
			tF_StuName_ShowAndEdit.setText(stu1.getName());
			if (stu1.getTeacher() == null) {
				tF_TutorName_ShowAndEdit.setText("无");
			} else
				tF_TutorName_ShowAndEdit.setText(stu1.getTeacher().getName());
			tF_StuNo_ShowAndEdit.setDisable(true);//学生学号不可修改
		}catch(NumberFormatException e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("输入格式有误，不是数字");
			alert.showAndWait();
		}catch(Exception e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("学号：" + stuNo + "的学生不存在");
			alert.showAndWait();
		}

	}

	/**
	 * 删除学生
	 * 
	 * @param event
	 */
	// Event Listener on Button[#btn_DelStu].onAction
	@FXML
	public void eventDelStu(ActionEvent event) {
		// TODO Autogenerated
		long stuNo = 0;
		try {
			stuNo = Long.parseLong(tF_StuNo_del.getText());// 获取学生的学号
			Student stu = new Student();
			stu.setId(stuNo);
			Student stu1 = StudentDao.deleteStudent(stu);

			tF_StuNo_del.setText(null);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText("学号：" + stu1.getId() + "姓名：" + stu1.getName() + "的学生删除成功！");
			alert.showAndWait();
		} catch (Exception e) {
			e.printStackTrace();
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("警告");
			alert.setHeaderText(null);
			alert.setContentText("删除失败！");
			alert.showAndWait();
		}

	}

	/**
	 * 删除教师
	 * 
	 * @param event
	 */
	// Event Listener on Button[#btn_DelTeach].onAction
	@FXML
	public void eventDelTeach(ActionEvent event) {
		// TODO Autogenerated
		long teachNo = 0;
		try {
			teachNo = Long.parseLong(tF_TeachNo_Del.getText());// 获取教师的工号
			Teacher t = new Teacher();
			t.setId(teachNo);
			Teacher t1 = TeacherDao.deleteTeacher(t);

			tF_TeachNo_Del.setText(null);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText("工号：" + t1.getId() + "姓名：" + t1.getName() + "的教师删除成功！");
			alert.showAndWait();
		} catch (Exception e) {
			e.printStackTrace();
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("警告");
			alert.setHeaderText(null);
			alert.setContentText("删除失败！");
			alert.showAndWait();
		}
	}
	/**
	 * 教师选择指导学生
	 * @param event
	 */
	// Event Listener on Button[#btn_Tutor_Teach_Stu_Save].onAction
	@FXML
	public void eventTutorTeachStuSave(ActionEvent event) {
		// TODO Autogenerated
		long tutorNo = 0;
		long stuNo = 0;
		try {
			tutorNo = Long.parseLong(tF_TutorNo.getText());// 获取指导教师的工号
			stuNo = Long.parseLong(tF_TeachedStuNo.getText());// 获取被指导学生的学号
			Teacher t = new Teacher();
			t.setId(tutorNo);
			Student stu = new Student();
			stu.setId(stuNo);
			
			Teacher t1 = TeacherDao.findTeacherByNo(t);
			Student stu1 = StudentDao.findStudentById(stu);
			
			if(stu1==null || t1==null) {
				throw new Exception();
			}
			stu1.setTeacher(t1);
			StudentDao.saveEdit(stu1);
			tF_TutorNo.setText(null);
			tF_TeachedStuNo.setText(null);
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setTitle("提示");
			alert.setHeaderText(null);
			alert.setContentText(t1.getName()+"教师成功选择学号为"+stu1.getId()+"的"+stu1.getName()+"同学为指导学生");
			alert.showAndWait();
		}catch(NumberFormatException e) {
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("请输入正确的数字格式");
			alert.showAndWait();
		}catch(Exception e) {
//			e.printStackTrace();
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("警告");
			alert.setHeaderText(null);
			alert.setContentText("当前输入的教师或学生不存在"+"\n"+"请输入正确的教师和学生号");
			alert.showAndWait();
		}
	}
	
	/**
	 * 显示教师的信息包括指导学生
	 * @param event
	 */
	// Event Listener on Button[#btn_ShowTeach].onAction
	@FXML
	public void eventShowTeach(ActionEvent event) {
		// TODO Autogenerated
		long tutorNo = 0;
		try {
			tF_TeachNo_ShowAndEdit.setDisable(false);
			tF_TeachNo_ShowAndEdit.setText(null);
			tF_TeachName_ShowAndEdit.setText(null);
			list.clear();
			
			tutorNo = Long.parseLong(tF_TeacherNo_edit.getText());// 获取教师的工号
			Teacher t = new Teacher();
			t.setId(tutorNo);
			Teacher t1 = TeacherDao.findTeacherByNo(t);
//			System.out.println(t1.getId());
//			System.out.println(t1.getName());
			tF_TeachNo_ShowAndEdit.setText(Long.toString(t1.getId()));
			tF_TeachName_ShowAndEdit.setText(t1.getName());
			
			Set<Student> students = t1.getStudents();
			for(Student stu : students) {
//				System.out.println(stu.getName());
				list.add(stu.getName());
			}
			listView_TeachedStu.setItems(list);
			tF_TeachNo_ShowAndEdit.setDisable(true);
			//使listView可编辑
//			listView_TeachedStu.setCellFactory(TextFieldListCell.forListView());
//			listView_TeachedStu.setEditable(true);
			

			
		}catch(NumberFormatException e) {
			exceptionHandling_ERROR("请输入正确的教师工号格式(数字)");
		}catch(NullPointerException e) {
			exceptionHandling_WARNING("工号为"+tutorNo+"的教师不存在");
		}

	}
	/**
	 * 保存修改的教师信息
	 * @param event
	 */
	// Event Listener on Button[#btn_EditTeacher_Save].onAction
	@FXML
	public void eventEditTeachSave(ActionEvent event) {
		// TODO Autogenerated
		long tutorNo =0;
		String tutorName = null;
		tutorNo = Long.parseLong(tF_TeacherNo_edit.getText());// 获取教师的工号
		tutorName = tF_TeachName_ShowAndEdit.getText();
		Teacher t = new Teacher();
		t.setId(tutorNo);
		t.setName(tutorName);
		Teacher t1 = TeacherDao.findTeacherByNo(t);
		t1.setName(tutorName);
		TeacherDao.saveEdit(t1);
		
	}
	
	// Event Listener on ListView[#listView_TeachedStu].onMouseClicked
	@FXML
	public void eventMouseClick(MouseEvent event) {
		// TODO Autogenerated
	/*	listView_TeachedStu.addEventHandler(MouseEvent.MOUSE_CLICKED, e ->{
			//双击
			if (e.getClickCount() == 2) {
//				String s = listView_TeachedStu.getSelectionModel().getSelectedItem();
				String s = listView_TeachedStu.getSelectionModel().selectedItemProperty().get();
				System.out.println(s);
				if(s!=null)
				dialogConfirm(s);  
			}
			
			});*/
		if (event.getClickCount() == 2) {
			String s = listView_TeachedStu.getSelectionModel().selectedItemProperty().get();
			System.out.println(s);
			if(s!=null)
			dialogConfirm(s);  
		}
	}
	
	//异常处理-错误
	public void exceptionHandling_ERROR(String message) {
		Alert alert = new Alert(AlertType.ERROR);
		alert.setTitle("错误");
		alert.setHeaderText(null);
		alert.setContentText(message);
		alert.showAndWait();
	}
	
	//异常处理-警告
	public void exceptionHandling_WARNING(String message) {
		Alert alert = new Alert(AlertType.WARNING);
		alert.setTitle("警告");
		alert.setHeaderText(null);
		alert.setContentText(message);
		alert.showAndWait();
	}
	
	public void dialogConfirm(String select) {
		Alert alert = new Alert(AlertType.CONFIRMATION);
//		alert.setTitle("Confirmation Dialog");
		alert.setTitle(null);
//		alert.setHeaderText("Look, a Confirmation Dialog");
		alert.setHeaderText(null);
		alert.setContentText("确定删除 "+select+" ?");

		Optional<ButtonType> result = alert.showAndWait();
		if (result.get() == ButtonType.OK){
		    // ... user chose OK
			Student stu = new Student();
			stu.setName(select);
			Student stu1 = StudentDao.findStudentByName(stu);
			stu1.setTeacher(null);
			StudentDao.saveEdit(stu1);
			list.remove(select);
		} else {
		    // ... user chose CANCEL or closed the dialog
		}
	}
	
}
